﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using PdfSharp.Pdf;
using PdfSharp.Pdf.IO;

namespace PdfExtractor
{
    public partial class ExtractorMainForm : Form
    {
        public ExtractorMainForm()
        {
            InitializeComponent();
        }

        private void btnBrowserFile_Click(object sender, EventArgs e)
        {
            if (rbtSingleFile.Checked)
            {
                openFileDialog1.Filter = "Pdf files(*.pdf)|*.pdf|All files(*.*)|*.*";
                if (openFileDialog1.ShowDialog() == DialogResult.OK)
                {
                    txtFileOrFolderPath.Text = openFileDialog1.FileName;
                    txtFileOrFolderPath.Enabled = false;
                }
            }
            else
            {
                if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
                {
                    txtFileOrFolderPath.Text = folderBrowserDialog1.SelectedPath;
                    txtFileOrFolderPath.Enabled = false;
                }
            }
        }

        private void btnProcess_Click(object sender, EventArgs e)
        {
            try
            {
                if (string.IsNullOrEmpty(txtFileOrFolderPath.Text))
                {
                    MessageBox.Show("请先选择要操作的文件或文件夹！");
                    return;
                }
                int iPageCount = 16;
                string strSuffix = "_16";
                if (rbtSingleFile.Checked)
                {
                    string entireFileFullName = txtFileOrFolderPath.Text.Trim();
                    this.ExtractPdfFile(entireFileFullName, iPageCount, strSuffix);
                }
                else
                {
                    string folderPath = txtFileOrFolderPath.Text.Trim();
                    DirectoryInfo dirInfo = new DirectoryInfo(folderPath);
                    this.ExtractPdfWithSubFolder(dirInfo, iPageCount, strSuffix);

                }
                MessageBox.Show("抽取完成！");
            }
            catch (Exception ex)
            {
                MessageBox.Show(string.Format("抽取PDF文件发生异常，异常信息：{0} 堆栈信息：{1}", ex.Message, ex.StackTrace));
            }
        }

        /// <summary>
        /// 从原文件抽取指定页数生成新的PDF文件
        /// </summary>
        /// <param name="fileFullName"></param>
        /// <param name="pageCount"></param>
        /// <param name="suffix"></param>
        private void ExtractPdfFile(string fileFullName, int pageCount, string suffix)
        {
            try
            {
                PdfDocument entirePdfFile = CompatiblePdfReader.Open(fileFullName, PdfDocumentOpenMode.Import);
                string smallFileFullName = fileFullName.Insert(fileFullName.LastIndexOf('.'), suffix);
                PdfDocument smallPdfFile = new PdfDocument();
                smallPdfFile.Version = entirePdfFile.Version;
                smallPdfFile.Info.Title = entirePdfFile.Info.Title;
                smallPdfFile.Info.Creator = entirePdfFile.Info.Creator;
                int iCount = pageCount;
                if (entirePdfFile.PageCount < iCount)
                {
                    iCount = entirePdfFile.PageCount;
                }
                for (int i = 0; i < iCount; i++)
                {
                    smallPdfFile.AddPage(entirePdfFile.Pages[i]);
                }
                smallPdfFile.Save(smallFileFullName);
            }
            catch (Exception ex)
            {

            }
        }

        private void ExtractPdfWithSubFolder(DirectoryInfo dirInfo, int pageCount, string suffix)
        {
            DirectoryInfo[] subDirArr = dirInfo.GetDirectories();
            if (subDirArr.Length > 0)
            {
                foreach (var directoryInfo in subDirArr)
                {
                    this.ExtractPdfWithSubFolder(directoryInfo, pageCount, suffix);
                }
            }
            FileInfo[] fiArr = dirInfo.GetFiles("*.pdf");
            foreach (var fileInfo in fiArr)
            {
                string fileName = fileInfo.Name;
                if (fileName.Substring(fileName.LastIndexOf('.') - 3, 3).Equals("_16"))
                {
                    continue;
                }
                this.ExtractPdfFile(fileInfo.FullName, pageCount, suffix);
            }
        }
    }
}
